﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Windows.Forms;

namespace TSNPro.Utils
{
    public static class WidgetUtils
    {
        // 执行操作，禁用控件，执行完成后恢复控件状态
        public static bool Execute(Control control, Action func, bool showExMsg = true)
        {
            bool ret = false;
            try
            {
                // 禁用控件
                if (control != null)
                {
                    control.Enabled = false;
                }

                // 执行传入的操作
                func();
                ret = true;
            }
            catch (Exception ex)
            {
                // 如果捕获异常，显示警告消息
                if (showExMsg)
                {
                    ShowWarning(ex.Message);
                }
                Console.WriteLine(ex);
            }
            finally
            {
                // 恢复控件状态
                if (control != null)
                {
                    control.Enabled = true;
                }
            }
            return ret;
        }

        public static void ShowWarning(string warningText)
        {
            MessageBox.Show(warningText, "Warning", MessageBoxButtons.OK, MessageBoxIcon.Warning);
        }
    }
}
